# -*- coding: utf-8 -*-
# Created by liangfuting on 2020/8/19
# Copyright (c) 2020 liangfuting. All rights reserved.

from django.shortcuts import render, redirect,reverse,HttpResponse
from django.urls import path
from django.utils.safestring import mark_safe

from stark.service.v1 import StarkHandler,get_manytomany,get_choice_text,BootStrapModelForm
from stark.forms.widgets import DateTimePickerInput
from django.db import transaction
from web.models import Customer,ConsultRecord,UserInfo


class PrivateCustomerModelForm(BootStrapModelForm):
    class Meta:
        model=Customer
        exclude=['consultant']

class PrivateCustomerHandler(StarkHandler):
    def display_consult_record(self,obj=None,is_header=None):
        if is_header:
            return '跟进记录'
        target_url=reverse("stark:web_consultrecord_list",kwargs={'customer_id':obj.pk})
        # print(target_url)
        return mark_safe("<a target='_blank' href='{}'>跟进记录</a>".format(target_url))

    def display_payment_record(self,obj=None,is_header=None):
        if is_header:
            return '缴费记录'
        target_url=reverse("stark:web_paymentrecord_list",kwargs={'customer_id':obj.pk})
        # print(target_url)
        return mark_safe("<a target='_blank' href='{}'>缴费记录</a>".format(target_url))

    list_display = ['name', 'qq', get_manytomany('课程','course'),get_choice_text('状态','status'),
                    display_consult_record,display_payment_record]
    model_form_class = PrivateCustomerModelForm

    def get_query_set(self,request,*args,**kwargs):

        # print(request.session.keys())
        # if 'user_info' not in request.session:
        #     # print(reverse('login'))
        #     return redirect(reverse('login'))
        user_id = request.session['user_info']['id']
        return self.model_class.objects.filter(consultant_id=user_id)

    def save(self,request,form,is_update,*args,**kwargs):
        if not is_update:
            #新增用户
            user_id = request.session['user_info']['id']
            form.instance.consultant_id=user_id
        #更新用户信息
        form.save()

    def action_multi_remove(self,request,*args,**kwargs):
        """
        批量申请帐户到私人账户
        :param request:
        :param args:
        :param kwargs:
        :return:
        """

        pk_list=request.POST.getlist('pk')
        user_id = request.session['user_info']['id']
        # print(pk_list)
        with transaction.atomic():
            customers = self.model_class.objects.filter(id__in=pk_list,consultant_id=user_id).select_for_update()
            if len(customers)==len(pk_list):
                #不能使用bulk_update
                # Customer.objects.bulk_update(customers)
                customers.update(consultant_id=None)
                # current_user.customer_set(customers)
        return redirect(self.reverse_list_url())



    action_multi_remove.text='批量移除到公共帐户'
    # action_list = self.get_action_list()
    # print(action_list)

    def get_action_list(self):
        #需要起一个新的名字
        action_list=[]
        action_list.extend(super(PrivateCustomerHandler,self).get_action_list())
        action_list.append(self.action_multi_remove)
        # print(action_list)
        return action_list

    def extra_urls(self):
        patterns = []
        # patterns.append(path('consult/record/<int:pk>/', self.wapper(self.consult_record), name=self.get_consult_record_url_name))
        # patterns.append(path('payment/record/<int:pk>/',self.wapper(self.payment_record),name=self.get_payment_record_url_name))
        # stark/ web/userinfo/ reset/password/<int:pk>/ [name='web_userinfo_reset_pwd']

        return patterns

    # def payment_record(self,request,pk):
    #     pass

    def consult_record(self,request,pk):
        record_list=ConsultRecord.objects.filter(customer__id=pk).all()
        #通过面板展示跟进记录，页面不同于stark的页面
        # print(pk,record_list)
        customer_obj=self.model_class.objects.filter(pk=pk).first()
        return render(request,'web/record_view.html',{'record_list':record_list,'customer':customer_obj})

    @property
    def get_consult_record_url_name(self):
        return self.get_url_name('record_view')

    def reverse_consult_record_url(self, *args, **kwargs):
        return self.reverse_common(self.get_consult_record_url_name, *args, **kwargs)

    # @property
    # def get_payment_record_url_name(self):
    #     print(self.get_url_name('payment_view'))
    #     return self.get_url_name('payment_view')
    #
    # def reverse_payment_record_url(self, *args, **kwargs):
    #     return self.reverse_common(self.get_payment_record_url_name, *args, **kwargs)
